/**
 * Anderground project - Subway maps processor application.
 * Copyright (C) 2008-2009 Eldar Abusalimov, Ilya Shurigyn
 * 
 * This file is part of Anderground.
 * 
 * Anderground is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * Anderground is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Anderground.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.anderground.modules.storage.xml;

import java.util.LinkedList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 */
public abstract class HierarchyHandler extends DefaultHandler {

	private LinkedList<HierarchyHandler> parentHandlers = new LinkedList<HierarchyHandler>();
	private String currentName = "";

	/**
	 * @param childHandler
	 *            the new {@link HierarchyHandler} to push to the parentHandlers
	 *            stack
	 */
	protected void enter(HierarchyHandler childHandler) {
		childHandler.parentHandlers.addFirst(this);
		childHandler.setRoot(getRoot());
	}

	/**
	 * @return the popped {@link HierarchyHandler} from the parentHandlers stack
	 *         if the stack is not empty or this otherwise
	 */
	protected HierarchyHandler leave() {
		if (!parentHandlers.isEmpty()) {
			HierarchyHandler handler = parentHandlers.removeFirst();
			return handler;
		}
		return this;
	}

	@Override
	public final void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		try {
			currentName = name.intern();
			enter(onStartChild(currentName, attributes));
		} catch (RuntimeException e) {
			throw new SAXException("runtime exception", e);
		}
	}

	@Override
	public final void endElement(String uri, String localName, String name)
			throws SAXException {
		try {
			leave().onEndChild(this, name.intern());
		} catch (RuntimeException e) {
			throw new SAXException("runtime exception", e);
		}
	}

	@Override
	public final void characters(char[] val, int offset, int length)
			throws SAXException {
		int start = 0;
		// left trim
		while ((start < length) && (val[offset + start] <= ' ')) {
			start++;
		}
		// right trim
		while ((start < length) && (val[offset + length - 1] <= ' ')) {
			length--;
		}
		// avoid empty string creation
		if (length == start) {
			return;
		}
		// replace all repeating whitespaces with single space
		int whiteCount = 0;
		boolean wasWhite = false;
		for (int i = offset + start; i < offset + length; i++) {
			if (val[i + whiteCount] <= ' ') {
				val[i + whiteCount] = ' ';
				if (wasWhite) {
					whiteCount++;
					length--;
					i--;
				}
				wasWhite = true;
			} else {
				wasWhite = false;
			}
			val[i] = val[i + whiteCount];
		}
		// In spite of the fact that this replacement allows us to use
		// line-break in the text, it is not recommended because of a bug
		// (?) in parser used by the Android (in such cases it considers the
		// text as few consecutive characters() events).

		try {
			onNonWhiteString(currentName, new String(val, offset + start,
					length - start));
		} catch (RuntimeException e) {
			throw new SAXException("runtime exception", e);
		}
	}

	/**
	 * 
	 * @param name
	 *            the interned name of the element (it may be compared with
	 *            another interned strings directly by == operator).
	 * @param attrs
	 *            the attributes attached to the element.
	 * @return a desired {@link HierarchyHandler} to handle a child hierarchy.
	 * @throws SAXException
	 */
	protected HierarchyHandler onStartChild(String name, Attributes attrs)
			throws SAXException {
		return this;
	}

	/**
	 * 
	 * @param childHandler
	 *            a {@link HierarchyHandler} that has been used to handle the
	 *            child's hierarchy.
	 * @param name
	 *            the interned name of the element (it may be compared with
	 *            another interned strings directly by == operator).
	 * @throws SAXException
	 */
	protected void onEndChild(HierarchyHandler childHandler, String name)
			throws SAXException {
	}

	/**
	 * 
	 * @param elementName
	 *            the interned name of current element (it may be compared with
	 *            another interned strings directly by == operator).
	 * @param string
	 *            the trimmed characters string.
	 * @throws SAXException
	 */
	protected void onNonWhiteString(String elementName, String string)
			throws SAXException {
	}

	protected abstract void setRoot(HierarchyHandler root);

	protected abstract HierarchyHandler getRoot();

}